import 'dart:convert';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../http/Api.dart';
import '../../http/HttpUtil.dart';
import '../../util/SignUtil.dart';
import '../../base/Constant.dart';
import '../../entity/goods_list_entity.dart';
import '../../liz_home/goods/GoodsDetail.dart';
import '../../util/AppSaveInfoUtil.dart';
import 'package:flutter_slidable/flutter_slidable.dart';

class CollectGoodsListPage extends StatefulWidget {
  CollectGoodsListPage({Key key}) : super(key: key);

  _CollectGoodsListPageState createState() => _CollectGoodsListPageState();
}

class _CollectGoodsListPageState extends State<CollectGoodsListPage> {
  List<GoodsModelData> homeListData = new List();
  var _scaffoldKey = new GlobalKey<ScaffoldState>();
  GlobalKey _stackKey = GlobalKey();
  EasyRefreshController _controller = new EasyRefreshController();
  int page = 1;
  int currentShow = 0; //0 正常 1 网格
  String token;
  final SlidableController slidableController = SlidableController();
  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);

    return Container(
      child: new Stack(
            key: _stackKey,
            children: <Widget>[
              new Column(
                children: <Widget>[
                  new Container(
                    height: MediaQuery.of(context).size.height -
                        kToolbarHeight -
                        ScreenUtil.getInstance().setHeight(DP_120) -
                        MediaQueryData.fromWindow(window).padding.top,
                    color: f0Color,
                    child: new EasyRefresh(
                      controller: _controller,
                      header: MaterialHeader(),
                      footer: MaterialFooter(),
                      enableControlFinishLoad: true,
                      enableControlFinishRefresh: true,
                      child: currentShow == 0
                          ? ListView.separated(
                              itemBuilder: _renderRow,
                              separatorBuilder:
                                  (BuildContext context, int index) {
                                return Container(
                                  color: divideColor,
                                  height: 1,
                                );
                              },
                              itemCount: homeListData == null
                                  ? 0
                                  : homeListData.length)
                          : GridView.builder(
                              shrinkWrap: true,
                              gridDelegate:
                                  SliverGridDelegateWithFixedCrossAxisCount(
                                      crossAxisCount: 2,
                                      mainAxisSpacing: 10.0,
                                      crossAxisSpacing: 10.0,
                                      childAspectRatio: 0.62),
                              itemBuilder: (context, index) {
                                return getItemContainer(context, index);
                              },
                              itemCount: homeListData == null
                                  ? 0
                                  : homeListData.length,
                            ),
                      onRefresh: () async {
                        page = 1;
                        loadList();
                      },
                      onLoad: () async {
                        page++;
                        loadList();
                      },
                    ),
                  ),
                ],
              ),
            ],
          ),
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    var price = RichText(
      textAlign: TextAlign.left,
      text: TextSpan(style: TextStyle(color: Colors.red), children: [
        TextSpan(text: '¥', style: TextStyle(fontSize: 12.0)),
        TextSpan(
            text: homeListData[index].price, style: TextStyle(fontSize: 18.0)),
        TextSpan(
          text: homeListData[index].old_price,
          style: TextStyle(
              fontSize: 12.0,
              color: Colors.grey,
              decoration: TextDecoration.lineThrough,
              decorationColor: Colors.grey),
        ),
      ]),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
    return Slidable(
        actionPane: SlidableStrechActionPane(),
        controller: slidableController,
        actionExtentRatio: 0.25,
        secondaryActions: <Widget>[
          IconSlideAction(
            caption: '取消收藏',
            color: Colors.red,
            icon: Icons.delete,
            closeOnTap: true,
            onTap: () {
              del(homeListData[index].goods_id);
            },
          ),
        ],
        child:  new GestureDetector(
      onTap: () {
        //处理点击事件
        GoodsModelData model = homeListData[index];

        Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
          return GoodsDetailPage(
            goods_id: model.goods_id,
            img: model.img,
          );
        }));
      },
      child: Container(
        padding: EdgeInsets.all(10),
        color: white,
        child: new Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            homeListData[index].img == ""
                ? Image.asset('images/pic_default.png',
                    width: ScreenUtil.getInstance().setWidth(180),
                    fit: BoxFit.fill,
                    height: ScreenUtil.getInstance().setWidth(180))
                : Image.network(
                    Api.ImgBaseUrl+homeListData[index].tmp_img,
                    width: ScreenUtil.getInstance().setHeight(180),
                    height: ScreenUtil.getInstance().setHeight(180),
                    fit: BoxFit.fill,
                  ),
            Expanded(
              flex: 1,
              child: Container(
                padding: EdgeInsets.fromLTRB(10, 5, 5, 5),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      homeListData[index].goods_name,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          fontSize: ScreenUtil.getInstance().setSp(28),
                          color: black,
                          fontWeight: FontWeight.w400),
                    ),
                    Row(
                      children: <Widget>[
                        Expanded(
                          flex: 1,
                          child: price,
                        ),
                        Container(
                          margin: EdgeInsets.all(kMargin5),
                          child: Text('已售' + homeListData[index].sales_volume,
                              style: TextStyle(
                                  fontSize: 12.0, color: Colors.grey)),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    ));
  }

  //商品单个cell
  getItemContainer(BuildContext context, int index) {
    var price = RichText(
      textAlign: TextAlign.left,
      text: TextSpan(style: TextStyle(color: Colors.red), children: [
        TextSpan(text: '¥', style: TextStyle(fontSize: 12.0)),
        TextSpan(
            // text: shopData[index].zk_final_price,
            text: homeListData[index].price,
            style: TextStyle(fontSize: 18.0)),
        TextSpan(
          // text: shopData[index].reserve_price,
          text: homeListData[index].old_price,
          style: TextStyle(
              fontSize: 12.0,
              color: Colors.grey,
              decoration: TextDecoration.lineThrough,
              decorationColor: Colors.grey),
        ),
      ]),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
    // var quanHeader = Container(
    //   width: ScreenUtil().setWidth(40),
    //   height: ScreenUtil().setWidth(34),
    //   decoration: BoxDecoration(
    //     image: DecorationImage(
    //       image: AssetImage("images/item_youhuiquan_header.png"),
    //       fit: BoxFit.cover,
    //     ),
    //   ),
    // );
    // var quan = Container(
    //   width: ScreenUtil().setWidth(70),
    //   height: ScreenUtil().setWidth(34),
    //   decoration: BoxDecoration(
    //     image: DecorationImage(
    //       image: AssetImage("images/item_youhuiquan_footer.png"),
    //       fit: BoxFit.cover,
    //     ),
    //   ),
    //   child: Center(
    //       child: Text(
    //     shopData[index].coupon_amount == null
    //         ? '0元'
    //         : shopData[index].coupon_amount + '元',
    //     style: TextStyle(color: Colors.white, fontSize: 10),
    //   )),
    // );
    var yongjin = Container(
      margin: EdgeInsets.fromLTRB(kMargin20, 0, kMargin20, 0),
      height: ScreenUtil().setWidth(34),
      color: Color.fromRGBO(250, 226, 226, 1),
      child: Center(
          child:
              // Text('预估赚¥' + shopData[index].commission,
              //     style: TextStyle(color: Colors.red, fontSize: 10))),
              Text('预估赚¥', style: TextStyle(color: Colors.red, fontSize: 10))),
    );
    return new GestureDetector(
        onTap: () {
          //处理点击事件
          GoodsModelData model = homeListData[index];

          Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
            return GoodsDetailPage(
              goods_id: model.goods_id,
              img: model.img,
            );
          }));

          // var gasIds=model.gasid;
          // Navigator.push(
          //     context,
          //     MaterialPageRoute(
          //         //导航打开新视图
          //         builder: (context) =>
          //             ShopDetailPage(model: model) //打开第二个页面，并传值，传递值的名称是model
          //         ));
        },
        child: Container(
            color: Colors.white,
            margin: EdgeInsets.fromLTRB(kMargin10, 0, kMargin10, 0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                homeListData[index].img == ''
                    ? Image.asset('images/pic_default.png')
                    : Image.network(
                        Api.BaseUrl +
                            'public/upload/' +
                            homeListData[index].img.replaceAll('\\', '/'),
                        width: (ScreenUtil.getInstance().setWidth(750) - kMargin20) / 2,
                        height: (ScreenUtil.getInstance().setWidth(750) - kMargin20) / 2,
                      ),
                Text(homeListData[index].goods_name, maxLines: 2),
                Container(
                  margin: EdgeInsets.all(kMargin5),
                  child: price,
                ),
                Container(
                  margin: EdgeInsets.all(kMargin5),
                  child: Text('已售' + '商品销量',
                      style: TextStyle(fontSize: 12.0, color: Colors.grey)),
                ),
                // Container(
                //   margin: EdgeInsets.all(kMargin5),
                //   child: Row(
                //     children: <Widget>[
                //       Expanded(
                //         flex: 1,
                //         child: Row(
                //           children: <Widget>[quanHeader, quan],
                //         ),
                //       ),
                //       Expanded(flex: 2, child: yongjin)
                //     ],
                //   ),
                // )
              ],
            )));
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getString(TOKEN).then((value) {
      token = value;
      if (value == null) {
        Navigator.of(context).pushNamed('login');
      } else {
        loadList();
      }
    });
  }

  loadList() async {
    Map map = new Map.from({
      "sign_type": createSignType(Api.URL_GOODSCOLLECT_LIST),
      "token": token,
    });
    Response<String> response =
        await HttpUtil().post(Api.URL_GOODSCOLLECT_LIST, data: getSign(map));
    Map userMap = json.decode(response.data);
    print(userMap);
    GoodsModelEntity itemEntity = new GoodsModelEntity.fromJson(userMap);
    print(userMap);
    if (itemEntity.code == 1) {
      if (mounted) {
        setState(() {
          if (page == 1) {
            homeListData.clear();
            homeListData = itemEntity.data;
          } else {
            homeListData.addAll(itemEntity.data);
          }
        });
      }
    }
  }
  del(String goods_id)async{
    Map map = new Map.from({
      "sign_type": createSignType(Api.URL_GOODSCOLLECT_CANCEL),
      "token": token,
      'goods_id':goods_id
    });
    Response<String> response =
        await HttpUtil().post(Api.URL_GOODSCOLLECT_CANCEL, data: getSign(map));
        Map userMap = json.decode(response.data);
        if (userMap['code'] == 1&&mounted) {
loadList();
        }
  }
}
